<?php

include_once "CzApiEnum.php";
class CzOrder
{
    public $params;
    public $db;
    public $user;
    public $orderReSubmitLimit = 9000;
    public $phoneSubmitMax = 5;

    protected $validate_mobile_key;
    protected $validateMobileUrl;


    public function __construct($params, $db, $user)
    {
        global $config;
        $this->validate_mobile_key = $config['validate_mobile_key'];
        $this->validateMobileUrl = $config['validateMobileUrl'];

        $this->params = $params;
        $this->db = $db;
        $this->user = $user;
    }
    public function checkOrder()
    {
        $mobile = $this->params['mobile'] ?? '';
        $spec_code = $this->params['spec_code'] ?? "szhd50";
        $user_order_sn = $this->params['user_order_sn'] ?? '';
        // $callback_url = $this->params['callback_url'] ?? '';
        if (strlen($user_order_sn) > 32) {
            error(CzApiEnum::USER_ORDER_SN_OUT, CzApiEnum::USER_ORDER_SN_OUT_CODE);
        }
        if (!is_numeric($mobile)) {
            error(CzApiEnum::MOBILE_FORMAT_ERROR, CzApiEnum::MOBILE_FORMAT_ERROR_CODE);
        }
        $mobile_pref = substr($mobile, 0, 7);
        //获取号码归属地
        $mobile_info = $this->db->db_getRow('SELECT * FROM phone WHERE phone =:phone limit 1', [
            ':phone' => $mobile_pref
        ]);
        if (!$mobile_info) {
            error(CzApiEnum::GET_MOBILE_AREA_INFO_FAIL, CzApiEnum::GET_MOBILE_AREA_INFO_FAIL_CODE);
        }
        $isBlank = $this->db->db_getRow('SELECT * FROM cz_mobile_blank WHERE mobile =:mobile limit 1', [
            ':mobile' => $mobile
        ]);
        if ($isBlank) {
            error(CzApiEnum::MOBILE_IS_BLANK, CzApiEnum::MOBILE_IS_BLANK_CODE);
        }
        $city_id = $mobile_info['area_code'];

        //20220424 预防多个城市id的数据
        if (strpos($city_id, '/') !== false) {
            $city_id_exp = explode("/", $city_id);
            $city_id = $city_id_exp[0];
        }

        $isp_name = $mobile_info['isp'];
        $isp = 0;
        switch ($isp_name) {
            case '移动':
                $isp = 1;
                break;
            case '联通':
                $isp = 2;
                break;
            case '电信':
                $isp = 3;
                break;
        }
        $area_info = $this->db->db_getRow('SELECT * FROM areas WHERE id =:id limit 1', [
            ':id' => $city_id
        ]);
        if (!$area_info) {
            error(CzApiEnum::AREA_INFO_NOT_EXIST, CzApiEnum::AREA_INFO_NOT_EXIST_CODE);
        }
        $province_id = $area_info['parent_id'];

        $spec_info = $this->db->db_getRow('SELECT * FROM cz_spec WHERE spec_code =:spec_code limit 1', [
            ':spec_code' => $spec_code
        ]);
        if (!$spec_info) {
            error(CzApiEnum::SPEC_NOT_EXIST, CzApiEnum::SPEC_NOT_EXIST_CODE);
        }
        if ($spec_info['status'] == 0) {
            error(CzApiEnum::SPEC_UNSALE, CzApiEnum::SPEC_UNSALE_CODE);
        }

        $spec_id = $spec_info['id'];
        $product_id = $spec_info['product_id'];

        $product_info = $this->db->db_getRow('SELECT * FROM cz_product WHERE id =:id limit 1', [
            ':id' => $product_id
        ]);
        if (!$product_info) {
            error(CzApiEnum::PRODUCT_NOT_EXIST, CzApiEnum::PRODUCT_NOT_EXIST_CODE);
        }
        if ($product_info['status'] == 0) {
            error(CzApiEnum::PRODUCT_UNSALE, CzApiEnum::PRODUCT_UNSALE_CODE);
        }
        if ($product_info['province_id'] > 0 && $province_id != $product_info['province_id']) {
            error(CzApiEnum::MOBILE_NOT_MATH_PRODUCT, CzApiEnum::MOBILE_NOT_MATH_PRODUCT_CODE);
        }
        if ($product_info['city_id'] > 0 && $city_id != $product_info['city_id']) {
            error(CzApiEnum::MOBILE_NOT_MATH_PRODUCT, CzApiEnum::MOBILE_NOT_MATH_PRODUCT_CODE);
        }


        //获取客户产品
        // $user_id = $this->user['id'];
        // $user = $this->db->db_getRow('SELECT * FROM sys_users WHERE id =:uid limit 1', [
        //     ':uid' => intval($user_id)
        // ]);
        // // 验证是否有api提交权限
        // if (!$user['can_api']) {
        //     error(CzApiEnum::USER_NO_API_PERMIT, CzApiEnum::USER_NO_API_PERMIT_CODE);
        // }
        // 验证限充
        $productLimit = $this->db->db_getRow('SELECT * FROM product_limit WHERE product_id =:product_id and status = 1 limit 1', [
            ':product_id' => intval($product_id)
        ]);
        if ($productLimit) {
            // if ($spec_info['is_limit']) {
            // 开启限充，获取限制限充的号码
            // 获取限充规则
            // $productLimit = $this->db->db_getRow('SELECT * FROM product_limit WHERE spec_id =:spec_id and product_id =:product_id and status = 1 limit 1', [
            //     ':spec_id' => intval($spec_id),
            //     ':product_id' => intval($product_id)
            // ]);
            $limit_type = $productLimit['limit_type'];
            $limit_value = $productLimit['limit_value'];
            $limit_type_value = $productLimit['limit_type_value'];
            switch ($limit_type) {
                case 'forever':
                    // 获取用户充值次数
                    $end = "";
                    $start = '';
                    break;
                case 'cur_day':
                    $end = (strtotime(date('Ymd')) + 60 * 60 * 24 - 1);
                    $start = (strtotime(date('Ymd')));
                    break;
                case 'cur_month':
                    $start = strtotime(date('Ym01'));
                    $end = strtotime(date('Ymt')) + 60 * 60 * 24 - 1;
                    break;
                case 'cur_year':
                    $start = strtotime(date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, intval(date('Y')))));
                    $end = strtotime(date('Ymd H:i:s'));
                    break;
                case 'hour':
                    // 多少小时内限充
                    $end = strtotime(date('Ymd H:i:s'));
                    $start = $end - $limit_type_value * 3600;
                    break;
                case 'day':
                    $end = strtotime(date('Ymd H:i:s'));
                    $start = $end - $limit_type_value * 3600 * 24;
                    break;
                case 'month':
                    $end = strtotime(date('Ymd H:i:s'));
                    $start = $end - $limit_type_value * 3600 * 24 * 30;  //月算30天
                    break;
                case 'year':
                    $end = strtotime(date('Ymd H:i:s'));
                    $start = $end - $limit_type_value * 3600 * 24 * 365;  //年算365天
                    break;
                case 'time_range':
                    $limit_time = json_decode($productLimit['limit_time'], true);
                    $start = intval($limit_time[0] / 1000); //毫秒换秒
                    $end = intval($limit_time[1] / 1000); //毫秒换秒
                    // logger("11" . $start);
                    // logger("22" . $end);
                    break;
                default:
                    break;
            }
            if ($start && $end) {
                $is_success_count = $this->db->db_getRow(
                    'SELECT count(*) as count FROM cz_order WHERE order_status =:order_status AND product_id =:product_id AND mobile =:mobile AND updated_at between :start_time and :end_time limit 1',
                    [
                        ':order_status' => 3,
                        ':mobile' => $mobile,
                        ':product_id' => intval($product_id),
                        ':start_time' => $start,
                        ':end_time' => $end,
                    ]
                );
                $is_handing_count = $this->db->db_getRow(
                    'SELECT count(*) as count FROM cz_order WHERE order_status in (1, 2, 5, 6) AND product_id =:product_id AND mobile =:mobile AND updated_at between :start_time and :end_time limit 1',
                    [
                        ':mobile' => $mobile,
                        ':product_id' => intval($product_id),
                        ':start_time' => $start,
                        ':end_time' => $end,
                    ]
                );
            } else {
                // 限制下单不需要添加sys_user_id 为商户,因为产品是针对手机限充
                // 永久
                $is_success_count = $this->db->db_getRow(
                    'SELECT count(*) as count FROM cz_order WHERE order_status =:order_status AND product_id =:product_id AND mobile =:mobile AND updated_at between :start_time and :end_time limit 1',
                    [
                        ':order_status' => 3,
                        ':mobile' => $mobile,
                        ':product_id' => intval($product_id),
                        ':start_time' => $start,
                        ':end_time' => $end,
                    ]
                );
                $is_handing_count = $this->db->db_getRow(
                    'SELECT count(*) as count FROM cz_order WHERE order_status in (1, 2, 5, 6) AND product_id =:product_id AND mobile =:mobile AND updated_at between :start_time and :end_time limit 1',
                    [
                        ':mobile' => $mobile,
                        ':product_id' => intval($product_id),
                        ':start_time' => $start,
                        ':end_time' => $end,
                    ]
                );
            }
            if ($is_success_count['count'] >= $limit_value) {
                // return error('当前手机号当前产品被限制充值,请选择其他产品进行充值!');
                // error('is_success_count:' . json_encode($is_success_count) . "is_handing_count" . $is_handing_count, 500);
                error(CzApiEnum::ORDER_LIMIT_SUCCESS, CzApiEnum::ORDER_LIMIT_SUCCESS_CODE);
            }
            if ($is_success_count['count'] + $is_handing_count['count'] >= $limit_value) {
                error(CzApiEnum::ORDER_LIMIT_HANDING, CzApiEnum::ORDER_LIMIT_HANDING_CODE);
                // return error('当前手机号当前产品被限制充值,且已经提交过,耐心等待上一笔充值结果后再提交!');
            }
        }
        // 获取用户配置的上限次数
        $phoneSubmitMax =  $this->phoneSubmitMax;
        //获取当天手机号下单次数 
        $curMobileCount = $this->db->db_getRow(
            'SELECT count(*) as count FROM cz_order WHERE order_status =:order_status AND spec_id =:spec_id AND mobile =:mobile AND updated_at between :start_time and :end_time limit 1',
            [
                ':order_status' => 4,
                ':mobile' => $mobile,
                ':spec_id' => intval($spec_id),
                ':start_time' => strtotime(date('Y-m-d', time())),
                ':end_time' => time(),
            ]
        );

        if ($curMobileCount['count'] >= $phoneSubmitMax) {
            // '当前手机号提交上限，请隔天再试'
            error(CzApiEnum::PHONE_SUBMIT_MAX, CzApiEnum::PHONE_SUBMIT_MAX_CODE);
        }
        // error($curMobileCount['count'], CzApiEnum::PHONE_SUBMIT_MAX_CODE);
        // if ($user['group_id'] > 0) {
        //     //客户分组产品
        //     $user_group_product =  $this->db->db_getRow(
        //         'SELECT * FROM cz_user_group_product WHERE product_id =:product_id AND spec_id =:spec_id AND user_group_id =:user_group_id limit 1',
        //         [
        //             ':product_id' => intval($product_id),
        //             ':spec_id' => intval($spec_id),
        //             ':user_group_id' => intval($user['group_id'])
        //         ]
        //     );


        //     if (!$user_group_product) {
        //         error(CzApiEnum::NO_USER_PRODUCT, CzApiEnum::NO_USER_PRODUCT_CODE);
        //     }
        // } else {
        //     //客户产品
        //     $user_product =  $this->db->db_getRow(
        //         'SELECT * FROM cz_customer_product WHERE product_id =:product_id AND spec_id =:spec_id AND user_id =:user_id limit 1',
        //         [
        //             ':product_id' => intval($product_id),
        //             ':spec_id' => intval($spec_id),
        //             ':user_id' => intval($user['id'])
        //         ]
        //     );
        //     if (!$user_product) {
        //         error(CzApiEnum::NO_USER_PRODUCT, CzApiEnum::NO_USER_PRODUCT_CODE);
        //     }
        // }
        success(['data' => []], '验证通过');
    }
    public function validateMobile($mobile)
    {
        // 先从本地数据库验证
        $return_data = [
            "code" => 200,
            "is_trans" => 0,
            "is_has" => 0,
            "area" =>  NULL,
            "isp" =>  NULL,
            "msg" =>  ''
        ];
        $mobile_info = $this->db->db_getRow('SELECT * FROM mobile_is_trans WHERE mobile =:mobile limit 1', [
            ':mobile' => $mobile
        ]);
        if ($mobile_info) {
            $return_data['is_trans'] = 1;
            $return_data['is_has'] = 1;
            return $return_data;
        }

        $post_data = [
            "apikey" => $this->validate_mobile_key,
            "mobile" => $mobile,
        ];
        $headers = [
            'Content-Type: application/json',
        ];
        // var_dump($this->validateMobileUrl);
        $res = $this->httpRequest($this->validateMobileUrl, "POST", $post_data);
        // return $res;
        // var_dump($res);
        $return_arr = json_decode($res, true);
        $return_data['msg'] =  $return_arr['reason'] ?? "";

        if ($return_arr['code'] == 0) {

            if (isset($return_arr['result'])) {
                $return_data['area'] = $return_arr['result']['Area'] ?? "";
                $return_data['isp'] = $return_arr['result']['Init_isp'] ?? "";
            }

            if ($return_arr['result']['res'] == 0) {
                $return_data['is_trans'] = 0;
            } else {
                $return_data['is_trans'] = 1;
            }
        } else {
            // if (isset($return_arr['code'])) {
            //     // 查询异常可正常下单
            //     logger('接口查询异常' . $return_data['msg']);
            // }
            // logger('接口查询异常' . $return_data['msg']);
            $return_data['code'] = 200;
            $return_data['is_trans'] = 0;
        }
        return $return_data;
    }
    public function orderSubmit()
    {
        $mobile = $this->params['mobile'] ?? '';
        $spec_code = $this->params['spec_code'] ?? 0;
        $user_order_sn = $this->params['user_order_sn'] ?? '';
        $callback_url = $this->params['callback_url'] ?? '';


        if (strlen($user_order_sn) > 32) {
            error(CzApiEnum::USER_ORDER_SN_OUT, CzApiEnum::USER_ORDER_SN_OUT_CODE);
        }

        if (!is_numeric($mobile)) {
            error(CzApiEnum::MOBILE_FORMAT_ERROR, CzApiEnum::MOBILE_FORMAT_ERROR_CODE);
        }
        //20220527 获取黑名单号码

        $isBlank = $this->db->db_getRow('SELECT * FROM cz_mobile_blank WHERE mobile =:mobile limit 1', [
            ':mobile' => $mobile
        ]);
        if ($isBlank) {
            error(CzApiEnum::MOBILE_IS_BLANK, CzApiEnum::MOBILE_IS_BLANK_CODE);
        }

        $mobile_pref = substr($mobile, 0, 7);

        $isp_name = "";
        $city_id = 0;
        $province = "";
        $city = "";
        $is_trans = 0;

        //获取号码归属地
        $mobile_info = $this->db->db_getRow('SELECT * FROM phone WHERE phone =:phone limit 1', [
            ':phone' => $mobile_pref
        ]);
        if (!$mobile_info) {
            // 查询归属地
            $areaValidate = $this->validateMobile($mobile);
            if ($areaValidate['code'] == 200) {

                $is_trans = $areaValidate['is_trans'];
                if (!$areaValidate['is_has']) {
                    // 携号转网入库
                    $time = time();
                    $mobile_sql = "INSERT INTO mobile_is_trans (id, mobile, updated_at, created_at) VALUES (NULL, {$mobile}, {$time}, {$time});";
                    $sth = $this->db->pdo->prepare($mobile_sql);
                    $sth->execute([]);
                    $sth = null;
                }
                if ($areaValidate['area']) {
                    $area_arr = explode('-', $areaValidate['area']);
                    $province = $area_arr[0];
                    $city = $area_arr[1];
                    $isp_name = $areaValidate['isp'];
                    // 获取area_code

                    // $new_area_info = DB::table('areas')->where('province_short_name', $province)->where('city_short_name', $city)->first();
                    $new_area_info = $this->db->db_getRow('SELECT * FROM areas WHERE province_short_name =:province_short_name AND city_short_name =:city_short_name limit 1', [
                        ':province_short_name' => $province,
                        ':city_short_name' => $city,
                    ]);
                    $city_id = $new_area_info['id'];
                    // var_dump($areaValidate);
                    // 保存至数据库
                    $phone_data = [
                        "pref" => substr($mobile, 0, 3),
                        "phone" => substr($mobile, 0, 7),
                        "province" => $province,
                        "city" => $city,
                        "isp" => $isp_name,
                        "post_code" => $new_area_info['zip_code'],
                        "city_code" => $new_area_info['city_code'],
                        "area_code" => $city_id,
                    ];
                    $phone_sql = "insert into phone set ";
                    foreach ($phone_data as $key => $val) {
                        $phone_sql .= "{$key}='{$val}',";
                    }
                    $phone_sql = substr($phone_sql, 0, (strlen($phone_sql) - 1));

                    $sth = $this->db->pdo->prepare($phone_sql);
                    $sth->execute([]);
                    $sth = null;
                } else {
                    // 这种情况是三方没有返回地区
                    return error('获取归属地失败');
                }
                if ($is_trans) {
                    return error('携号转网无法充值');
                }
            } else {
                return error('获取归属地失败');
            }
            // error(CzApiEnum::GET_MOBILE_AREA_INFO_FAIL, CzApiEnum::GET_MOBILE_AREA_INFO_FAIL_CODE);
        } else {
            $city_id = $mobile_info['area_code'];
            $isp_name = $mobile_info['isp'];
            $province = $mobile_info['province'];
            $city = $mobile_info['city'];
        }


        // $city_id = $mobile_info['area_code'];

        //20220424 预防多个城市id的数据
        if (strpos($city_id, '/') !== false) {
            $city_id_exp = explode("/", $city_id);
            $city_id = $city_id_exp[0];
        }

        // $isp_name = $mobile_info['isp'];
        $isp = 0;
        switch ($isp_name) {
            case '移动':
                $isp = 1;
                break;
            case '联通':
                $isp = 2;
                break;
            case '电信':
                $isp = 3;
                break;
        }
        $area_info = $this->db->db_getRow('SELECT * FROM areas WHERE id =:id limit 1', [
            ':id' => $city_id
        ]);
        if (!$area_info) {
            error(CzApiEnum::AREA_INFO_NOT_EXIST, CzApiEnum::AREA_INFO_NOT_EXIST_CODE);
        }
        $province_id = $area_info['parent_id'];

        $spec_info = $this->db->db_getRow('SELECT * FROM cz_spec WHERE spec_code =:spec_code limit 1', [
            ':spec_code' => $spec_code
        ]);
        if (!$spec_info) {
            error(CzApiEnum::SPEC_NOT_EXIST, CzApiEnum::SPEC_NOT_EXIST_CODE);
        }
        if ($spec_info['status'] == 0) {
            error(CzApiEnum::SPEC_UNSALE, CzApiEnum::SPEC_UNSALE_CODE);
        }

        $spec_id = $spec_info['id'];
        $product_id = $spec_info['product_id'];

        $product_info = $this->db->db_getRow('SELECT * FROM cz_product WHERE id =:id limit 1', [
            ':id' => $product_id
        ]);
        if (!$product_info) {
            error(CzApiEnum::PRODUCT_NOT_EXIST, CzApiEnum::PRODUCT_NOT_EXIST_CODE);
        }
        if ($product_info['status'] == 0) {
            error(CzApiEnum::PRODUCT_UNSALE, CzApiEnum::PRODUCT_UNSALE_CODE);
        }
        if ($product_info['isp'] != $isp) {
            error(CzApiEnum::MOBILE_ISP_NO_MATH, CzApiEnum::MOBILE_ISP_NO_MATH_CODE);
        }
        if ($product_info['province_id'] > 0 && $province_id != $product_info['province_id']) {
            error(CzApiEnum::MOBILE_NOT_MATH_PRODUCT, CzApiEnum::MOBILE_NOT_MATH_PRODUCT_CODE);
        }
        if ($product_info['city_id'] > 0 && $city_id != $product_info['city_id']) {
            error(CzApiEnum::MOBILE_NOT_MATH_PRODUCT, CzApiEnum::MOBILE_NOT_MATH_PRODUCT_CODE);
        }
        $old_title = $product_info['title'] . $spec_info['face_value'];
        //获取客户产品
        $user_id = $this->user['id'];
        $user = $this->db->db_getRow('SELECT * FROM sys_users WHERE id =:uid limit 1', [
            ':uid' => intval($user_id)
        ]);
        // 验证是否有api提交权限
        if (!$user['can_api']) {
            error(CzApiEnum::USER_NO_API_PERMIT, CzApiEnum::USER_NO_API_PERMIT_CODE);
        }
        // 验证限充
        $productLimit = $this->db->db_getRow('SELECT * FROM product_limit WHERE product_id =:product_id and status = 1 limit 1', [
            ':product_id' => intval($product_id)
        ]);
        if ($productLimit) {
            // 开启限充，获取限制限充的号码
            // 获取限充规则
            // spec_id =:spec_id and
            // ':spec_id' => intval($spec_id),
            // $productLimit = $this->db->db_getRow('SELECT * FROM product_limit WHERE product_id =:product_id and status = 1 limit 1', [
            //     ':product_id' => intval($product_id)
            // ]);
            $limit_type = $productLimit['limit_type'];
            $limit_value = $productLimit['limit_value'];
            $limit_type_value = $productLimit['limit_type_value'];
            switch ($limit_type) {
                case 'forever':
                    // 获取用户充值次数
                    $end = "";
                    $start = '';
                    break;
                case 'cur_day':
                    $end = (strtotime(date('Ymd')) + 60 * 60 * 24 - 1);
                    $start = (strtotime(date('Ymd')));
                    break;
                case 'cur_month':
                    $start = strtotime(date('Ym01'));
                    $end = strtotime(date('Ymt')) + 60 * 60 * 24 - 1;
                    break;
                case 'cur_year':
                    $start = strtotime(date("Y-m-d H:i:s", mktime(0, 0, 0, 1, 1, intval(date('Y')))));
                    $end = strtotime(date('Ymd H:i:s'));
                    break;
                case 'hour':
                    // 多少小时内限充
                    $end = strtotime(date('Ymd H:i:s'));
                    $start = $end - $limit_type_value * 3600;
                    break;
                case 'day':
                    $end = strtotime(date('Ymd H:i:s'));
                    $start = $end - $limit_type_value * 3600 * 24;
                    break;
                case 'month':
                    $end = strtotime(date('Ymd H:i:s'));
                    $start = $end - $limit_type_value * 3600 * 24 * 30;  //月算30天
                    break;
                case 'year':
                    $end = strtotime(date('Ymd H:i:s'));
                    $start = $end - $limit_type_value * 3600 * 24 * 365;  //年算365天
                    break;
                case 'time_range':
                    $limit_time = json_decode($productLimit['limit_time'], true);
                    $start = intval($limit_time[0] / 1000); //毫秒换秒
                    $end = intval($limit_time[1] / 1000); //毫秒换秒
                    // logger("11" . $start);
                    // logger("22" . $end);
                    break;
                default:
                    break;
            }
            if ($start && $end) {
                // AND spec_id =:spec_id
                // ':spec_id' => intval($spec_id),
                $is_success_count = $this->db->db_getRow(
                    'SELECT count(*) as count FROM cz_order WHERE order_status =:order_status  AND product_id =:product_id AND mobile =:mobile AND updated_at between :start_time and :end_time limit 1',
                    [
                        ':order_status' => 3,
                        ':mobile' => $mobile,
                        ':product_id' => intval($product_id),
                        ':start_time' => $start,
                        ':end_time' => $end,
                    ]
                );
                // spec_id =:spec_id AND 
                // ':spec_id' => intval($spec_id),
                $is_handing_count = $this->db->db_getRow(
                    'SELECT count(*) as count FROM cz_order WHERE order_status in (1, 2, 5, 6) AND product_id =:product_id AND mobile =:mobile AND updated_at between :start_time and :end_time limit 1',
                    [
                        ':mobile' => $mobile,
                        ':product_id' => intval($product_id),
                        ':start_time' => $start,
                        ':end_time' => $end,
                    ]
                );
            } else {
                // 限制下单不需要添加sys_user_id 为商户,因为产品是针对手机限充
                // 永久
                // ':spec_id' => intval($spec_id),
                // AND spec_id =:spec_id 
                $is_success_count = $this->db->db_getRow(
                    'SELECT count(*) as count FROM cz_order WHERE order_status =:order_status AND product_id =:product_id AND mobile =:mobile AND updated_at between :start_time and :end_time limit 1',
                    [
                        ':order_status' => 3,
                        ':mobile' => $mobile,
                        ':product_id' => intval($product_id),
                        ':start_time' => $start,
                        ':end_time' => $end,
                    ]
                );
                // spec_id =:spec_id AND 
                // ':spec_id' => intval($spec_id),
                $is_handing_count = $this->db->db_getRow(
                    'SELECT count(*) as count FROM cz_order WHERE order_status in (1, 2, 5, 6) AND product_id =:product_id AND mobile =:mobile AND updated_at between :start_time and :end_time limit 1',
                    [
                        ':mobile' => $mobile,
                        ':product_id' => intval($product_id),
                        ':start_time' => $start,
                        ':end_time' => $end,
                    ]
                );
            }
            if ($is_success_count['count'] >= $limit_value) {
                // return error('当前手机号当前产品被限制充值,请选择其他产品进行充值!');
                // error('is_success_count:' . json_encode($is_success_count) . "is_handing_count" . $is_handing_count, 500);
                error(CzApiEnum::ORDER_LIMIT_SUCCESS, CzApiEnum::ORDER_LIMIT_SUCCESS_CODE);
            }
            if ($is_success_count['count'] + $is_handing_count['count'] >= $limit_value) {
                error(CzApiEnum::ORDER_LIMIT_HANDING, CzApiEnum::ORDER_LIMIT_HANDING_CODE);
                // return error('当前手机号当前产品被限制充值,且已经提交过,耐心等待上一笔充值结果后再提交!');
            }

            // $productBlackInfo = CzProductBlack::where('spec_id', $spec_id)->where('product_id', $product_id)->where('status', 1)->first();
            // $productBlackInfo = $this->db->db_getRow('SELECT * FROM cz_product_black WHERE spec_id =:spec_id and product_id =:product_id and status = 1 limit 1', [
            //     ':spec_id' => intval($spec_id),
            //     ':product_id' => intval($product_id)
            // ]);
            // if ($productBlackInfo) {
            //     $is_handing_count = $this->db->db_getRow(
            //         'SELECT count(*) as count FROM cz_order WHERE order_status in (1, 2, 5, 6) AND spec_id =:spec_id AND product_id =:product_id AND mobile =:mobile AND updated_at between :start_time and :end_time limit 1',
            //         [
            //             ':mobile' => $mobile,
            //             ':spec_id' => intval($spec_id),
            //             ':product_id' => intval($product_id),
            //             ':start_time' => $spec_info['limit_time'],
            //             ':end_time' => time(),
            //         ]
            //     );
            //     // error($is_handing_count['count']);
            //     if ($is_handing_count['count'] >= $productBlackInfo['limit_num']) {
            //         // error($is_handing_count['count']);
            //         error(CzApiEnum::ORDER_LIMIT_HANDING, CzApiEnum::ORDER_LIMIT_HANDING_CODE);
            //     }
            //     $is_success_count = $this->db->db_getRow(
            //         'SELECT count(*) as count FROM cz_order WHERE order_status =:order_status AND spec_id =:spec_id AND product_id =:product_id AND mobile =:mobile AND updated_at between :start_time and :end_time limit 1',
            //         [
            //             ':order_status' => 3,
            //             ':mobile' => $mobile,
            //             ':spec_id' => intval($spec_id),
            //             ':product_id' => intval($product_id),
            //             ':start_time' => $spec_info['limit_time'],
            //             ':end_time' => time(),
            //         ]
            //     );
            //     if ($is_success_count['count'] >= $productBlackInfo['limit_num']) {
            //         // return error('当前手机号被限制充值!');
            //         error(CzApiEnum::ORDER_LIMIT_SUCCESS, CzApiEnum::ORDER_LIMIT_SUCCESS_CODE);
            //     }
            //     if ($is_handing_count['count'] + $is_success_count['count'] >= $productBlackInfo['limit_num']) {
            //         error(CzApiEnum::ORDER_LIMIT_SUCCESS, CzApiEnum::ORDER_LIMIT_SUCCESS_CODE);
            //         // return error('当前手机号被限制充值,且已经提交过,耐心等待上一笔充值结果后再提交!');
            //     }
            // }
        }
        // 获取用户配置的上限次数
        $phoneSubmitMax = $user['phone_max'] ?? $this->phoneSubmitMax;
        //获取当天手机号下单次数 
        $curMobileCount = $this->db->db_getRow(
            'SELECT count(*) as count FROM cz_order WHERE order_status =:order_status AND spec_id =:spec_id AND mobile =:mobile AND updated_at between :start_time and :end_time limit 1',
            [
                ':order_status' => 4,
                ':mobile' => $mobile,
                ':spec_id' => intval($spec_id),
                ':start_time' => strtotime(date('Y-m-d', time())),
                ':end_time' => time(),
            ]
        );

        if ($curMobileCount['count'] >= $phoneSubmitMax) {
            // '当前手机号提交上限，请隔天再试'
            error(CzApiEnum::PHONE_SUBMIT_MAX, CzApiEnum::PHONE_SUBMIT_MAX_CODE);
        }
        $is_split =  0;
        // 获取充值面值
        $face_value = $spec_info['face_value'];
        $hf_type = $product_info['hf_type'];

        $product_ids = $this->db->db_getCol('select id from cz_product where (province_id = :province_id1 or province_id = :province_id2) and (city_id = :city_id1 or city_id = :city_id2) and isp = :isp and hf_type = :hf_type and status = :status', [
            ':province_id1' => $province_id,
            ':province_id2' => 0,
            ':city_id1' => $city_id,
            ':city_id2' => 0,
            ':isp' => $isp,
            ':hf_type' => $hf_type,
            ':status' => 1,
        ]);
        $product_ids_str = implode(',', $product_ids);
        // var_dump('product_ids_str');
        // var_dump($product_ids_str);

        // $spec_ids = $this->db->db_getCol('SELECT id FROM cz_spec WHERE product_id IN (' . $str . ')', []);
        $spec_ids = $this->db->db_getCol('SELECT id FROM cz_spec WHERE status = :status and face_value = :face_value and product_id IN (' . $product_ids_str . ')', [
            ":face_value" => $face_value,
            ":status" => 1
        ]);
        $spec_ids_str = implode(',', $spec_ids);

        // var_dump($face_value);
        // var_dump($product_ids);
        // var_dump($spec_ids);
        // var_dump(implode(',', $product_ids));
        // return 11;

        if ($user['group_id'] > 0) {
            //客户分组产品
            $old_user_group_product =  $this->db->db_getRow(
                'SELECT * FROM cz_user_group_product WHERE product_id =:product_id AND spec_id =:spec_id AND user_group_id =:user_group_id limit 1',
                [
                    ':product_id' => intval($product_id),
                    ':spec_id' => intval($spec_id),
                    ':user_group_id' => intval($user['group_id'])
                ]
            );

            if (!$old_user_group_product) {
                error(CzApiEnum::NO_USER_PRODUCT, CzApiEnum::NO_USER_PRODUCT_CODE);
            }
            $cur_user_group_product_id = $old_user_group_product['id'];
            if ($product_info['is_split']) {
                $user_group_product = $this->db->db_getAll("select * from cz_user_group_product where user_group_id = :user_group_id  and spec_id in (" . $spec_ids_str . ") and product_id in (" . $product_ids_str . ") order by id desc", [
                    ':user_group_id' => intval($user['group_id']),
                ]);
                if (!$user_group_product) {
                    error(CzApiEnum::NO_USER_PRODUCT, CzApiEnum::NO_USER_PRODUCT_CODE);
                }

                // 优先匹配分省
                foreach ($user_group_product as $key => $val) {
                    $product_id = $val['product_id'];
                    $product = $this->db->db_getRow('SELECT * FROM cz_product WHERE id =:id limit 1', [
                        ':id' => $product_id
                    ]);
                    if ($product['city_id']) {
                        $cur_user_group_product_id = $val['id'];
                        break;
                    } else if ($product['province_id']) {
                        $cur_user_group_product_id = $val['id'];
                        break;
                    }
                }
            }
            if ($old_user_group_product['id'] != $cur_user_group_product_id) {
                $new_user_group_product = $this->db->db_getRow("select * from cz_user_group_product where id = :id limit 1", [
                    ':id' => intval($cur_user_group_product_id),
                ]);
                $is_split =  1;
            } else {
                $new_user_group_product = $old_user_group_product;
            }

            // if ($new_user_group_product['id'] != $old_user_group_product['id']) {
            // }
            // $user_group_product = UserGroupProduct::whereIn('product_id', $product_ids)
            //     ->whereIn('spec_id', $spec_ids)
            //     ->where('user_group_id', $user->group_id)->get();

            $user_price = $old_user_group_product['user_group_price'];

            $is_loop = $new_user_group_product['is_loop'];
            $submit_order_count = $new_user_group_product['submit_order_count'];
            $channel_group_id = $new_user_group_product['channel_group_id'];
            $user_product_timeout = $new_user_group_product['timeout'] ?? 0;

            // 使用新的产品规格
            if ($spec_info['id'] != $new_user_group_product['spec_id']) {
                $spec_info = $this->db->db_getRow('SELECT * FROM cz_spec WHERE id =:id limit 1', [
                    ':id' => $new_user_group_product['spec_id']
                ]);
            }
            if ($product_info['id'] != $new_user_group_product['product_id']) {
                $product_info = $this->db->db_getRow('SELECT * FROM cz_product WHERE id =:id limit 1', [
                    ':id' => $new_user_group_product['product_id']
                ]);
            }

            $new_title = $product_info['title'] . $spec_info['face_value'];
        } else {
            //客户产品
            $old_user_product =  $this->db->db_getRow(
                'SELECT * FROM cz_customer_product WHERE product_id =:product_id AND spec_id =:spec_id AND user_id =:user_id limit 1',
                [
                    ':product_id' => intval($product_id),
                    ':spec_id' => intval($spec_id),
                    ':user_id' => intval($user['id'])
                ]
            );
            if (!$old_user_product) {
                error(CzApiEnum::NO_USER_PRODUCT, CzApiEnum::NO_USER_PRODUCT_CODE);
            }
            $user_product = $this->db->db_getAll("select * from cz_customer_product where user_id = :user_id  and spec_id in (" . $spec_ids_str . ") and product_id in (" . $product_ids_str . ") order by id desc", [
                ':user_id' => intval($user['id']),
            ]);
            if (!$user_product) {
                error(CzApiEnum::NO_USER_PRODUCT, CzApiEnum::NO_USER_PRODUCT_CODE);
            }
            $cur_user_product_id = $old_user_product['id'];
            if ($product_info['is_split']) {
                // 优先匹配分省
                foreach ($user_product as $key => $val) {
                    $product_id = $val['product_id'];
                    $product = $this->db->db_getRow('SELECT * FROM cz_product WHERE id =:id limit 1', [
                        ':id' => $product_id
                    ]);
                    if ($product['city_id']) {
                        $cur_user_product_id = $val['id'];
                        break;
                    } else if ($product['province_id']) {
                        $cur_user_product_id = $val['id'];
                        break;
                    }
                }
            }
            if ($cur_user_product_id != $old_user_product['id']) {
                $new_user_product =  $this->db->db_getRow(
                    'SELECT * FROM cz_customer_product WHERE id =:id limit 1',
                    [
                        ':id' => intval($cur_user_product_id),
                    ]
                );
                $is_split =  1;
            } else {
                $new_user_product = $old_user_product;
            }

            // 给用户扣款使用的是不分省市的价格
            $user_price = $old_user_product['user_price'];

            $is_loop = $new_user_product['is_loop'];
            $submit_order_count = $new_user_product['submit_order_count'];
            // $channel_group_id = $user_product['channel_group_id'];
            $user_product_timeout = $new_user_product['timeout'] ?? 0;

            // 使用新的产品规格
            if ($spec_info['id'] != $new_user_product['spec_id']) {
                $spec_info = $this->db->db_getRow('SELECT * FROM cz_spec WHERE id =:id limit 1', [
                    ':id' => $new_user_product['spec_id']
                ]);
            }
            if ($product_info['id'] != $new_user_product['product_id']) {
                $product_info = $this->db->db_getRow('SELECT * FROM cz_product WHERE id =:id limit 1', [
                    ':id' => $new_user_product['product_id']
                ]);
            }
            $new_title = $product_info['title'] . $spec_info['face_value'];
        }
        $time = time();
        $order_data = [
            'order_sn' => 'CZ' . date("YmdH") . sprintf('%04d', $user['id']) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999)),
            'product_name' => $product_info['title'],
            'mobile' => $mobile,
            'face_value' => $spec_info['face_value'],
            'cost' => $user_price,
            'price' => $user_price,
            // 'area_name' => $mobile_info['province'] . '-' . $mobile_info['city'],
            'area_name' => $province . '-' . $city,
            'province_id' => $province_id,
            'city_id' => $city_id,
            'order_status' => $spec_info['is_cache'] == 1 ? 5 : 1, //5是压单
            'isp' => $product_info['isp'],
            'biz_type' => $product_info['type'],
            'hf_type' => $product_info['hf_type'],
            'product_id' => $product_info['id'],
            'spec_id' => $spec_info['id'],
            'is_loop' => $is_loop,
            'submit_order_count' => $submit_order_count ?? $this->orderReSubmitLimit,
            'submit_from' => 'api' . ($is_split ? "|" . ($old_title . '下分为->' . $new_title) : ""),
            'is_auto' => $spec_info['is_auto'],
            'created_at' => $time,
            'updated_at' => $time,
            'create_by' => $user['id'],
            'update_by' => $user['id'],
            'callback_url' => $callback_url
        ];
        //默认客户订单号为 平台订单号
        $order_data['user_order_sn'] = $user_order_sn ?? $order_data['order_sn'];
        if ($user_order_sn) {
            $has_user_order_sn = $this->db->db_getRow('SELECT * FROM cz_order WHERE user_order_sn =:user_order_sn limit 1', [
                ':user_order_sn' => $user_order_sn
            ]);
            if ($has_user_order_sn) {
                error(CzApiEnum::ORDER_USER_SN_FAIL, CzApiEnum::ORDER_USER_SN_FAIL_CODE);
            }
        }
        if ($user['id'] != 75) {
            $validateRes = $this->validateMobile($mobile);
            if (isset($validateRes['code']) && $validateRes['code'] == 200 && $validateRes['is_trans'] != 0) {
                // 无效号码直接返回
                if (!$validateRes['is_has']) {
                    // 保存转网记录
                    $time = time();
                    $mobile_sql = "INSERT INTO mobile_is_trans (id, mobile, updated_at, created_at) VALUES (NULL, {$mobile}, {$time}, {$time});";
                    $sth = $this->db->pdo->prepare($mobile_sql);
                    $sth->execute([]);
                    $sth = null;
                }
                error(CzApiEnum::MOBILE_IS_TRANS, CzApiEnum::MOBILE_IS_TRANS_CODE);
            }
        }

        $balance_log_data = [
            'order_sn' => $order_data['order_sn'],
            'money' => $user_price,
            'bf_balance' => $user['balance'],
            'af_balance' => $user['balance'] - $user_price,
            'bank' => '',
            'type' => 3,
            'remark' => "{$mobile},充值[{$product_info['title']}{$spec_info['face_value']}]，消费{$user_price}元",
            'user_id' => $user['id'],

            'created_at' => $time,
            'updated_at' => $time,
        ];
        /*
        //如果是快充话费 增加超时
        if($order_data['biz_type'] == 1 && $order_data['hf_type'] == 1 && $user['kc_timeout'] > 0){
            $order_data['timeout'] = time() + intval($user['kc_timeout']);
        }
        */
        //用户分配产品的超时时间
        if ($user_product_timeout > 0) {
            $order_data['timeout'] = time() + intval($user_product_timeout);
        }

        $order_sql = "insert into cz_order set ";
        foreach ($order_data as $key => $val) {
            $order_sql .= "{$key}='{$val}',";
        }
        $order_sql = substr($order_sql, 0, (strlen($order_sql) - 1));

        $balance_log_sql = "insert into balance_log set ";
        foreach ($balance_log_data as $key => $val) {
            $balance_log_sql .= "{$key}='{$val}',";
        }
        $balance_log_sql = substr($balance_log_sql, 0, (strlen($balance_log_sql) - 1));

        $user_dec_balance_sql = "update sys_users set balance = balance - {$user_price} where id = {$user['id']} AND balance >= " . ($user_price - $user['credit']);

        try {
            $this->db->pdo->beginTransaction();

            //扣除余额
            $sth = $this->db->pdo->prepare($user_dec_balance_sql);
            $sth->execute();
            if ($sth->rowCount() === 0) {
                $this->db->pdo->rollBack();
                error(CzApiEnum::BALANCE_NOT_ENOUGH, CzApiEnum::BALANCE_NOT_ENOUGH_CODE);
            }
            $sth = null;

            //资金记录
            $sth = $this->db->pdo->prepare($balance_log_sql);
            $sth->execute([]);
            $sth = null;

            //订单
            $sth = $this->db->pdo->prepare($order_sql);
            $sth->execute([]);
            $sth = null;

            $order_id = $this->db->pdo->lastInsertId();

            $this->db->pdo->commit();

            //自动订单且状态为1就推送去自动处理
            if ($order_data['is_auto'] == 1 && $order_data['order_status'] == 1) {
                sock_queue($order_id, 'queue_order');
            }

            success(['data' => [
                'user_order_sn' => $user_order_sn,
                'order_sn' => $order_data['order_sn'],
                'price' => $order_data['price'],
            ]], '下单成功');
        } catch (Exception $e) {
            $this->db->pdo->rollBack();
            $msg = $e->getMessage();
            error(CzApiEnum::ORDER_SUBMIT_FAIL . ":{$msg}", CzApiEnum::ORDER_SUBMIT_FAIL_CODE);
        }
        //推送到队列

    }

    public function queryOrder()
    {
        if (!isset($this->params['order_sn']) && !isset($this->params['user_order_sn'])) {
            error('缺少订单号参数', CzApiEnum::PARAMS_EMPTY_CODE);
        }
        $order_sn = trim($this->params['order_sn'] ?? '');
        $user_order_sn = trim($this->params['user_order_sn'] ?? '');
        //查询订单
        if ($order_sn) {
            $order = select_table_one($this->db, 'cz_order', [
                'order_sn' => $order_sn,
                'create_by' => $this->user['id'],
            ]);
        } else {
            $order = select_table_one($this->db, 'cz_order', [
                'user_order_sn' => $user_order_sn,
                'create_by' => $this->user['id'],
            ]);
        }

        if (!$order) {
            error(CzApiEnum::ORDER_NOT_EXIST, CzApiEnum::ORDER_NOT_EXIST_CODE);

            if ($order['create_by'] != $this->user['id']) {
                error(CzApiEnum::ORDER_NOT_BELONGS, CzApiEnum::ORDER_NOT_BELONGS_CODE);
            }
        }
        $text = '处理中';
        switch ($order['order_status']) {
            case 3:
                $text = '充值完成';
                break;
            case 4:
                $text = '充值失败';
                break;
            default:
                $text = '处理中';
                break;
        }
        success([
            'data' => [
                'order_status' => $order['order_status'],
                'order_status_text' => $text
            ]
        ], '获取成功');
    }

    public function queryBalance()
    {
        success([
            'data' => [
                'balance' => $this->user['balance'],
            ]
        ], '获取成功');
    }

    public function queryProduct()
    {
        $user_spec_id = [];
        if ($this->user['group_id'] > 0) {
            $this->params['user_group_id'] = $this->user['group_id'];
            //获取用户已分配产品面值
            $user_all_price = $this->db->db_getAll('SELECT spec_id,user_group_price as user_price FROM cz_user_group_product WHERE user_group_id =:user_group_id', [
                ':user_group_id' => $this->user['group_id']
            ]);
            foreach ($user_all_price as $item) {
                array_push($user_spec_id, $item['spec_id']);
            }
        } else {
            $this->params['user_id'] = $this->user['id'];
            //获取用户已分配产品面值
            $user_all_price = $this->db->db_getAll('SELECT spec_id,user_price FROM cz_customer_product WHERE user_id =:user_id', [':user_id' => $this->user['id']]);
            foreach ($user_all_price as $item) {
                array_push($user_spec_id, $item['spec_id']);
            }
        }
        if (count($user_spec_id) == 0) {
            error(CzApiEnum::NO_USER_PRODUCT, CzApiEnum::NO_USER_PRODUCT_CODE);
        }
        $user_all_price = $this->convert_arr_key($user_all_price, 'spec_id');

        $user_spec_id_str = implode(",", $user_spec_id);

        //查询用户分配的产品信息
        $user_product_list_sql = "SELECT `id`, `title`, `type`, `hf_type`, `isp`, `province_id`, `city_id`, `status` FROM
`cz_product` WHERE EXISTS
(
SELECT * FROM `cz_spec` WHERE `cz_product`.`id` = `cz_spec`.`product_id` AND `id` IN ({$user_spec_id_str})
)
";
        $user_product_list = $this->db->db_getAll($user_product_list_sql);

        $user_product_ids = [];
        foreach ($user_product_list as $k => $user_product) {
            if ($user_product['status'] == 1) {
                array_push($user_product_ids, $user_product['id']);
            }
        }

        //查询用户分配的面值信息
        $user_spec_list_sql = "SELECT `id`, `product_id`, `face_value`, `market_price`, `spec_code`, `status`
FROM `cz_spec`
WHERE `cz_spec`.`product_id` IN (" . implode(',', $user_product_ids) . ") AND
`id` IN ({$user_spec_id_str})";

        $user_spec_list = $this->db->db_getAll($user_spec_list_sql);

        //设置用户面值的价格
        $new_user_spec_list = [];
        foreach ($user_spec_list as $k => $user_spec) {
            $user_spec_list[$k]['user_price'] = $user_all_price[$user_spec['id']]['user_price'];
            $new_user_spec_list[$user_spec['product_id']][] = $user_spec_list[$k];
        }

        //组装面值到产品列表
        $area_ids = [];
        foreach ($user_product_list as $k => $user_product) {
            if (isset($new_user_spec_list[$user_product['id']])) {
                $user_product_list[$k]['specs'] = $new_user_spec_list[$user_product['id']];
            }
            array_push($area_ids, $user_product['province_id'], $user_product['city_id']);
        }
        //获取地区信息
        $area_ids = array_unique($area_ids);
        if (count($area_ids) > 0) {
            $area_sql = "select `id`, `short_name` from `areas` where `areas`.`id` in (" . implode(",", $area_ids) . ")";
            $area_list = $this->db->db_getAll($area_sql);
            $area_list = $this->convert_arr_key($area_list, 'id');
        }

        foreach ($user_product_list as $k => $user_product) {
            $user_product_list[$k]['province'] = $area_list[$user_product['province_id']]['short_name'] ?? '全省';
            $user_product_list[$k]['city'] = $area_list[$user_product['city_id']]['short_name'] ?? '全市';
        }

        success([
            'data' => $user_product_list
        ], '获取成功');
    }

    public function convert_arr_key($arr, $key_name)
    {
        $arr2 = array();
        foreach ($arr as $key => $val) {
            $arr2[$val[$key_name]] = $val;
        }
        return $arr2;
    }
    public function httpRequest($url, $method, $postfields = null, $cookie = '', $refer = '', $headers = array(), $debug = false)
    {
        //header("Content-type:text/html;charset=utf-8");
        $method = strtoupper($method);
        $ci = curl_init();
        /* Curl settings */
        curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        //        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0");
        curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36");
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 0); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
        curl_setopt($ci, CURLOPT_TIMEOUT, 120); /* 设置cURL允许执行的最长秒数*/
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);

        switch ($method) {
            case "POST":
                curl_setopt($ci, CURLOPT_POST, true);
                if (!empty($postfields)) {
                    $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                    curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
                }
                break;
            default:
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
                break;
        }
        $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
        curl_setopt($ci, CURLOPT_URL, $url);
        if ($ssl) {
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
            curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
        }
        //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
        curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        curl_setopt($ci, CURLOPT_COOKIE, $cookie);/* * *COOKIE带过去** */
        //伪造来源referer
        //        curl_setopt ($ci,CURLOPT_REFERER,'http://sb777.cn:8080/tohersystem/rechargeOrder.do?action=distribution&isDistribution=true');
        curl_setopt($ci, CURLOPT_REFERER, $refer);

        $response = curl_exec($ci);
        $requestinfo = curl_getinfo($ci);
        $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);

        if (!$response) {
            // 请求异常才记录
            $log_file_name = __DIR__ . '/../../../storage/logs/' . date("Y-m-d") . 'request.txt';
            file_put_contents($log_file_name, "--------请求信息：---------", FILE_APPEND);
            file_put_contents($log_file_name, "\r\n", FILE_APPEND);
            file_put_contents($log_file_name, json_encode($requestinfo) . "\r\n", FILE_APPEND);
            file_put_contents($log_file_name, '状态码:' . $http_code, FILE_APPEND);
            file_put_contents($log_file_name, "\r\n", FILE_APPEND);
            if ($method == 'POST') {
                file_put_contents($log_file_name, "--------请求参数：---------", FILE_APPEND);
                file_put_contents($log_file_name, "\r\n", FILE_APPEND);
                file_put_contents($log_file_name, $tmpdatastr . "\r\n", FILE_APPEND);
                file_put_contents($log_file_name, "\r\n", FILE_APPEND);
            }
        }
        if ($debug) {
            echo "=====post data======\r\n";
            var_dump($postfields);
            echo "=====info===== \r\n";
            print_r($requestinfo);
            echo "=====response=====\r\n";
            print_r($response);
        }
        curl_close($ci);
        return $response;
    }
}
